package com.zerox.controller;


import com.alibaba.fastjson.JSON;
import com.zerox.domain.TableVO;
import com.zerox.pojo.Supplier;
import com.zerox.pojo.SysUser;
import com.zerox.service.SupplierService;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/supplier")
public class SupplierController {

    @Autowired
    private SupplierService supplierService;

    @GetMapping("/tolist")
    public String toList() {
        return "supplier";
    }
    @GetMapping(value = "/list",produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String listSupplier(Integer page,Integer limit,String supContact){

        List<Supplier> list = supplierService.list(supContact ,page, limit);

        int count = supplierService.count(supContact);

        TableVO tableVO = new TableVO(0, count, list, "");

        String string = JSON.toJSONString(tableVO);

        return string;
    }
    @PostMapping("/add2")
    public String add2(Model model, HttpServletRequest request, @Valid Supplier supplier, BindingResult bindingResult, MultipartFile idPic) throws IOException {
        if (bindingResult.hasErrors()){
            List<FieldError>fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                model.addAttribute(fieldError.getField()+"Error", fieldError.getDefaultMessage());
            }
            return "add2";
        }
        if (idPic.getSize()>2000000){
            model.addAttribute("idPicError","文件超过2M不能上传");
            return "add";
        }
//        int result =supplierService.add(supplier);
//
//        if (result>0){
//            return "redirect:/supplier/tolist";
//        }
        String suffix = idPic.getOriginalFilename().substring(idPic.getOriginalFilename().lastIndexOf("."));
        if (".jpg.png".indexOf(suffix)==-1){
            model.addAttribute("idPicError","文件格式不正确，不能上传");
            return "add";
        }
        String path = request.getSession().getServletContext().getRealPath("statics")+ File.separator+"upload";
        String fileName = RandomUtils.nextInt(1000000)+"_pic"+suffix;
        File fileTo = new File(path+File.separator+fileName);

        if (!fileTo.exists()){
            fileTo.mkdirs();
        }

//        model.addAttribute("errorMsg","新增失败");
//
//        return "add2";
        idPic.transferTo(fileTo);

        supplier.setFileImg(fileName);
        int result = supplierService.add(supplier);
        if (result > 0){
            return "redirect:/supplier/tolist";
        }
        model.addAttribute("errorMsg","修改成功");
        return "add2";
    }

    @GetMapping("/delete2/{id}")
    @ResponseBody
    public String  delete(@PathVariable Integer id){
        int result = supplierService.delete(id);
        return result>0 ? "1" : "0";
    }
    @GetMapping("/toadd")
    public String toAdd() {
        return "add2";
    }
    @GetMapping("/view/{userId}")
    public String view(Model model,@PathVariable("userId") Integer id){
        Supplier supplier = supplierService.selectById(id);
        model.addAttribute("supplier",supplier);
        return "view2";
    }
    private Integer id;
    @GetMapping("/toupdate2/{id}")
    public String toUpdate(Model model,@PathVariable Integer id){
        this.id = id;
        Supplier supplier = supplierService.selectById(id);
        model.addAttribute("supplier",supplier);
        return "update2";
    }
    @PostMapping("/update2")
    public String update(Model model,@Valid Supplier supplier,BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            List<FieldError>fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                model.addAttribute(fieldError.getField()+"Error", fieldError.getDefaultMessage());
            }
            return "update2";
        }
        supplier.setId(id);
        int result = supplierService.updateById(supplier);
        if (result > 0){
            return "redirect:tolist";
        }
        model.addAttribute("errorMsg","新增失败");
        return "update2";
    }
    @GetMapping("/CodeSelect")
    @ResponseBody
    public String CodeSelect(String supCode){
        int supplier = supplierService.selectBysupCode(supCode);
        if (supplier>0){
            return "0";
        }else {
            return "1";
        }
    }
    
    @GetMapping("/supNameSelect")
    @ResponseBody
    public String supNameSelect(String supName){
        int supplier = supplierService.selectBySupName(supName);
        if (supplier>0){
            return "0";
        }else {
            return "1";
        }
    }
    @RequestMapping(value = "/find2",produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String find(Integer id,Model model){
        Supplier supplier = supplierService.selectById(id);
        model.addAttribute("user",supplier);
        return JSON.toJSONString(supplier);
    }
}
